package com.wk.slaveNodes;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;

import com.wk.database.DB_Mysql;
import com.wk.database.MasterMachine;
import com.wk.database.entity.Query;
import com.wk.job.Job;
import com.wk.job.heartbeat.slave.JobStateHeartbeatSource;
import com.wk.net.heartbeat.source.senders.TcpSender;

public class Slave {
	
	
	private LinkedBlockingQueue<Job> jobs = new LinkedBlockingQueue<>();
	private SynchronousQueue<Job> calculatingAJob = new SynchronousQueue<>();
	private JobStateHeartbeatSource heartbeatSource = null;
	
	Thread putToCalcu = null;
	Thread jobMonitor = null;
	Thread receive = null;
	Thread calculate = null;
	
	Job job = null;
	volatile boolean isWorking = true;
	volatile boolean isMonitor = false;
	
	public  void init(){
		System.out.println("init...");
		receive = new Thread(new RecieveJobs(jobs),"接受job任务");
		
		MasterMachine masterMachine = getMaster();
		if(masterMachine != null){
			System.out.println("主节点："+masterMachine.toString());
			heartbeatSource  = new JobStateHeartbeatSource(null, new TcpSender(masterMachine.ip, 8086), 10);
		}else{
		//TODO 如果heartbeatSource是null改如何处理？
		
		throw new RuntimeException("MasterMachine 为 null");
		}
		putToCalcu = new Thread(new PutToCalculating(jobs, calculatingAJob),"安排计算线程");
		calculate = new Thread(new Calculate(calculatingAJob,heartbeatSource),"计算线程");//计算线程
		System.out.println("inited...");
	}
	public void start(){
		System.out.println("staring...");
		if(receive != null ){
			receive.start();
		}
		if(putToCalcu != null ){
			putToCalcu.start();
		}
		if(calculate != null){
			calculate.start();
		}
		heartbeatSource.start();
		System.out.println("stared...");
	}
	
	
	public static void main(String[] args){
		Slave slave1 = new Slave();
		slave1.init();
		slave1.start();//开始
	}
	
	private MasterMachine getMaster(){
		Query<MasterMachine>  query = new Query<>(MasterMachine.class);
		try {
			query.connect(DB_Mysql.getConnection());
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		List<MasterMachine> results;
		try {
			results = query.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		if(results.isEmpty()){
			System.out.println("没有配置主节点");
			return null;
		}
		
		return results.get(0);
	}
	
}
